<?php

require_once BaseUtil::getModulePath("base")  .  '/services/BaseService.php';
require_once BaseUtil::getModulePath("trade") . '/models/AccountAgentTotalDao.php';
require_once BaseUtil::getModulePath("trade") . '/constants/TradeConstant.php';
require_once BaseUtil::getModulePath("trade") . '/models/AccountAgentTradeLogDao.php';
require_once BaseUtil::getModulePath("trade") . '/models/UserPointLogDao.php';
require_once BaseUtil::getModulePath("component") . '/Number.php';
require_once BaseUtil::getModulePath("systemlog").'/services/SystemLogService.php';
require_once BaseUtil::getModulePath("customer")  .  '/models/CustomerDao.php';

class TradeComponentService extends BaseService {
	
	
	   private $agentTotalDao;
	   
	   private $accountAgentTradeLogDao;
	   
	   private $systemLogService;
	   
	   private $customerDao;
	   
	   private $userPointLogDao;
	   
	   public function  __construct() {
	         parent::__construct();
	         $this->agentTotalDao = new AccountAgentTotalDao();
	         $this->agentTotalDao->setDb($this->db);
             $this->accountAgentTradeLogDao = new AccountAgentTradeLogDao();
             $this->accountAgentTradeLogDao->setDb($this->db);	  
             $this->customerDao = new CustomerDao();
             $this->customerDao->setDb($this->db);       
             $this->userPointLogDao = new UserPointLogDao();
             $this->userPointLogDao->setDb($this->db);                          
             $this->systemLogService = new SystemLogService();       
	   }
	   
	   /**
	    * freeze money
	    */
	   public function freezeMoney($userId,$tradeSum,$tradeType,$orderNum,$orderId,$tradeoperator){
	   	   
	   }
	   
	   /**
	    * check out money
	    */
	   public function checkoutMoney($userId,$tradeSum,$tradeType,$orderNum,$orderId,$tradeOperator = ""){	
	   	   $logType = "ADDACM";   	   
	   	   if(empty($tradeOperator)){
	   	   	   $tradeOperator = $this->getTradeOperator();
	   	   }
	   	   $agentTotal = $this->agentTotalDao->getInfoByUserId($userId);
	   	   if(empty($agentTotal)){
	   	   	   return false;
	   	   }
	   	   if($tradeType !=12 && $tradeType !=22 && $tradeType != 32){
	   	   	   return false;
	   	   }
	   	   //prepare account_agent_trade_logs data
	   	   $data = array();
	   	   $data['user_id'] = $userId;
	   	   $data['order_id'] = $orderId;
	   	   $data['order_num'] = $orderNum;
	   	   $data['trade_type'] = $tradeType;
	   	   $data['trade_sum'] = $tradeSum;
	   	   $data['trade_operator'] = $tradeOperator;
	   	   $data['status'] = 1;
	       $data['balance_prev'] = $agentTotal['balance'];
	       $data['debt_prev'] = $agentTotal['debt_balance'];
	       $data['freeze_prev'] = $agentTotal['freezed_balance'];
	       $data['usage_balance_prev'] = $agentTotal['usage_balance'];   
	       
           //update account_agent_totals
           $agentData = array();
	       $agentData['order_dealing_cnt']=$agentTotal['order_dealing_cnt'] - 1;
           $agentData['order_dealing_sum']=$agentTotal['order_dealing_sum'] - $tradeSum;
           $agentData['order_cnt']=$agentTotal['order_cnt'] + 1;
           $agentData['order_sum']=$agentTotal['order_sum'] + $tradeSum;
           $agentData['order_last_time'] = date("Y-m-d H:i:s");
           $agentData['order_last_type'] = TradeConstant::getTradeType($tradeType);
           if($tradeType == 12){
               $agentData['order_self_sale_sum']=$agentTotal['order_self_sale_sum'] + $tradeSum;
           }elseif($tradeType == 22){
               $agentData['order_auto_recv_sum']=$agentTotal['order_auto_recv_sum'] + $tradeSum;
           }elseif($tradeType == 32){
               $agentData['order_campus_sum']=$agentTotal['order_campus_sum'] + $tradeSum;
           }	

	       if($agentTotal['usage_balance']>=0){//当可用余额>0时直接减去冻结资金 不对 赊账进行任何操作

                //log添加账户增减记录
                $data['account_freeze_offset']= -$tradeSum;
                $data['account_balance_offset']= -$tradeSum;
                //total账户改变 
                $agentData['balance']=$agentTotal['balance']-$tradeSum;
                $agentData['freezed_balance']=$agentTotal['freezed_balance']-$tradeSum;


                $data['balance_now']=$agentData['balance'];
                $data['debt_now']=$agentTotal['debt_balance'];
                $data['freeze_now']=$agentData['freezed_balance'];
                $data['usage_balance_now']=$agentTotal['usage_balance'];
            }elseif($agentTotal['usage_balance']<0){//当可用余额<0时需要考虑账户的余额 不足的部分放入赊账

                if($agentTotal['balance']>=$tradeSum){//当账户余额大于等于交易金额
                    //log添加账户增减记录
                    $data['account_freeze_offset']=-$tradeSum;
                    $data['account_balance_offset']=-$tradeSum;
                    //total账户改变
                    $agentData['balance']=$agentTotal['balance']-$tradeSum;
                    $agentData['freezed_balance']=$agentTotal['freezed_balance']-$tradeSum;

                    $data['balance_now']=$agentData['balance'];
                    $data['debt_now']=$agentTotal['debt_balance'];
                    $data['freeze_now']=$agentData['freezed_balance'];
                    $data['usage_balance_now']=$agentTotal['usage_balance'];

                }else{//当账户余额小于等于交易金额
                    //账户余额与实扣款的差值
                    $less =  $tradeSum-$agentTotal['balance'];
                    if($less<=($agentTotal['debt_total']-$agentTotal['debt_balance'])){
                        $data['account_freeze_offset']=-$tradeSum;
                        $data['account_balance_offset']=-$agentTotal['balance'];
                        $data['account_usage_balance_offset']=$less;
                        $data['account_debt_balance_offset']=$less;

                        $agentData['balance']=0;
                        $agentData['freezed_balance']=$agentTotal['freezed_balance']-$tradeSum;
                        $agentData['debt_balance']=$agentTotal['debt_balance']+$less;
                        $agentData['usage_balance']=$agentTotal['usage_balance']+$less;

                        $data['balance_now']=$agentData['balance'];
                        $data['debt_now']=$agentData['debt_balance'];
                        $data['freeze_now']=$agentData['freezed_balance'];
                        $data['usage_balance_now']=$agentData['usage_balance'];
                    }else{
                        return false;
                    }
                }
            }    
            $logId = $this->accountAgentTradeLogDao->insertTradeLog($data);
	        if(!empty($logId)){
                $this->UpdateTradLogSN($logId,$tradeType);
            } 
            $this->systemLogService->insertSystemLog($logType,$this->getLoginUserName(),$data,array(),3);
            $this->agentTotalDao->updateAccountAgentTotalsByUserId($agentData,$userId);     
            $this->systemLogService->insertSystemLog($logType,$this->getLoginUserName(),$agentData,array('user_id'=>$userId),3);                 
	        return true;
	   }
	   
	    private function UpdateTradLogSN($id,$tradeType){
	        $data['sn'] = Number::getTradeLogSN($id,$tradeType);
	        $this->accountAgentTradeLogDao->updateLastTradeLog($data,$id);
	    }	   
	    
	    /**
	     * refund freezed money
	     */
	    public function refundFreezeMoney($userId,$tradeSum,$tradeType,$orderId,$orderNum,$tradeOperator = ""){
	         if(empty($tradeOperator)){
               $tradeOperator = $this->getTradeOperator();
             }
	    	 $agentTotal = $this->agentTotalDao->getInfoByUserId($userId);
             if(empty($agentTotal)){
                 return false;
             }	
             $data = array();  
	         $data['user_id']=$userId;
	         $data['order_id']=$orderId;
	         $data['order_num']=$orderNum;
	         $data['trade_type']=$tradeType;
	         $data['trade_sum']=$tradeSum;
	         $data['trade_operator']=$tradeOperator;
	         $data['status']=1;
	         //log表交易前账户的记录
	         $data['balance_prev'] = $agentTotal['balance'];
	         $data['debt_prev'] = $agentTotal['debt_balance'];
	         $data['freeze_prev'] = $agentTotal['freezed_balance'];
	         $data['usage_balance_prev'] = $agentTotal['usage_balance'];
	         $logType="ADDARF";	 
             //log添加账户增减记录
             $data['account_freeze_offset']=-$tradeSum;
             $data['account_usage_balance_offset']=$tradeSum;
             //total账户改变 
             $agentData = array();
             $agentData['usage_balance']=$agentTotal['usage_balance']+$tradeSum;
             $agentData['freezed_balance']=$agentTotal['freezed_balance']-$tradeSum;

             $agentData['order_dealing_cnt']=$agentTotal['order_dealing_cnt']-1;
             $agentData['order_dealing_sum']=$agentTotal['order_dealing_sum']-$tradeSum;

             $data['balance_now']=$agentTotal['balance'];
             $data['debt_now']=$agentTotal['debt_balance'];
             $data['freeze_now']=$agentData['freezed_balance'];
             $data['usage_balance_now']=$agentData['usage_balance'];	
             $logId = $this->accountAgentTradeLogDao->insertTradeLog($data);
             if(!empty($logId)){
                $this->UpdateTradLogSN($logId,$tradeType);
             } 
             $this->systemLogService->insertSystemLog($logType,$this->getLoginUserName(),$data,array(),3); 
             $this->agentTotalDao->updateAccountAgentTotalsByUserId($agentData,$userId);    
             $this->systemLogService->insertSystemLog($logType,$this->getLoginUserName(),$agentData,array('user_id'=>$userId),3);
             return true;                                                                 	
	    }
	    
	    /**
	     * refund checkout money
	     */
	    public function refundCheckoutMoney($userId,$tradeSum,$tradeType,$orderId,$orderNum,$tradeOperator = ""){
	         if(empty($tradeOperator)){
                $tradeOperator = $this->getTradeOperator();
             }             
	    	 $agentTotal = $this->agentTotalDao->getInfoByUserId($userId);
             if(empty($agentTotal)){
                 return false;
             }  
             $data = array();  
             $data['user_id']=$userId;
             $data['order_id']=$orderId;
             $data['order_num']=$orderNum;
             $data['trade_type']=$tradeType;
             $data['trade_sum']=$tradeSum;
             $data['trade_operator']=$tradeOperator;
             $data['status']=1;
             //log表交易前账户的记录
             $data['balance_prev'] = $agentTotal['balance'];
             $data['debt_prev'] = $agentTotal['debt_balance'];
             $data['freeze_prev'] = $agentTotal['freezed_balance'];
             $data['usage_balance_prev'] = $agentTotal['usage_balance'];
             $logType="ADDARM";
             $agentData = array();
             $agentData['order_cnt']=$agentTotal['order_cnt']-1;
             $agentData['order_sum']=$agentTotal['order_sum']-$tradeSum;
             if($tradeType==13){
                $agentData['order_self_sale_sum']=$agentTotal['order_self_sale_sum']-$tradeSum;
             }elseif($tradeType==23){
                $agentData['order_auto_recv_sum']=$agentTotal['order_auto_recv_sum']-$tradeSum;
             }elseif($tradeType==33){
                $agentData['order_campus_sum']=$agentTotal['order_campus_sum']-$tradeSum;
             }

             if($agentTotal['debt_balance']<=0){ //赊账金额小于0
                $data['account_balance_offset']=$tradeSum;
                $data['account_usage_balance_offset']=$tradeSum;

                $agentData['balance']=$agentTotal['balance']+$tradeSum;
                $agentData['usage_balance']=$agentTotal['usage_balance']+$tradeSum;

                $data['balance_now']=$agentData['balance'];
                $data['freeze_now']=$agentTotal['freezed_balance'];
                $data['usage_balance_now']=$agentData['usage_balance'];
                $data['debt_now']=$agentTotal['debt_balance'];
             }else{
                if($tradeSum>$agentTotal['debt_balance']){
                    $less = $tradeSum-$agentTotal['debt_balance'];
                    $data['account_balance_offset']=$less;
                    $data['account_usage_balance_offset']=$less;
                    $data['account_debt_balance_offset']=-$agentTotal['debt_balance'];

                    $agentData['balance']=$agentTotal['balance']+$less;
                    $agentData['usage_balance']=$agentTotal['usage_balance']+$less;
                    $agentData['debt_balance'] = 0;

                    $data['balance_now']=$agentData['balance'];
                    $data['freeze_now']=$agentTotal['freezed_balance'];
                    $data['usage_balance_now']=$agentData['usage_balance'];
                    $data['debt_now']=$agentData['debt_balance'];
                }else{
                    $less = $agentTotal['debt_balance']-$tradeSum;
                    $data['account_debt_balance_offset']=-$tradeSum;

                    $agentData['debt_balance'] = $less;

                    $data['balance_now']=$agentTotal['balance'];
                    $data['freeze_now']=$agentTotal['freezed_balance'];
                    $data['usage_balance_now']=$agentTotal['usage_balance'];
                    $data['debt_now']=$agentData['debt_balance'];
                }
             }  
             $logId = $this->accountAgentTradeLogDao->insertTradeLog($data);
             if(!empty($logId)){
                $this->UpdateTradLogSN($logId,$tradeType);
             } 
             $this->systemLogService->insertSystemLog($logType,$this->getLoginUserName(),$data,array(),3); 
             $this->agentTotalDao->updateAccountAgentTotalsByUserId($agentData,$userId);    
             $this->systemLogService->insertSystemLog($logType,$this->getLoginUserName(),$agentData,array('user_id'=>$userId),3);
             return true;                         
	    }
	    
	    /**
	     * add profit data
	     */
	    public function addProfit($userId,$tradeSum,$tradeType,$orderId,$orderNum,$tradeOperator = ""){
	        if(empty($tradeOperator)){
               $tradeOperator = $this->getTradeOperator();
            }            
	    	$agentTotal = $this->agentTotalDao->getInfoByUserId($userId);
            if(empty($agentTotal)){
                 return false;
            }  
            $data = array();  
            $data['user_id']=$userId;
            $data['order_id']=$orderId;
            $data['order_num']=$orderNum;
            $data['trade_type']=$tradeType;
            $data['trade_sum']=$tradeSum;
            $data['trade_operator']=$tradeOperator;
            $data['status']=1;  
	        //log表交易前账户的记录
	        $data['balance_prev']=$agentTotal['balance'];
	        $data['debt_prev']=$agentTotal['debt_balance'];
	        $data['freeze_prev']=$agentTotal['freezed_balance'];
	        $data['usage_balance_prev']=$agentTotal['usage_balance']; 

	        $agentData = array();
            $agentData['profit'] = $agentTotal['profit'] + $tradeSum;	        
	        if($agentTotal['debt_balance']<=0){ //赊账金额小于0
	            $data['account_balance_offset']=$tradeSum;
	            $data['account_usage_balance_offset']=$tradeSum;
	
	            $agentData['balance']=$agentTotal['balance']+$tradeSum;
	            $agentData['usage_balance']=$agentTotal['usage_balance']+$tradeSum;
	
	            $data['balance_now']=$agentData['balance'];
	            $data['freeze_now']=$agentTotal['freezed_balance'];
	            $data['usage_balance_now']=$agentData['usage_balance'];
	            $data['debt_now']=$agentTotal['debt_balance'];
	        }else{
	            if($tradeSum>$agentTotal['debt_balance']){
	                $less = $tradeSum-$agentTotal['debt_balance'];
	                $data['account_balance_offset']=$less;
	                $data['account_usage_balance_offset']=$less;
	                $data['account_debt_balance_offset']=-$agentTotal['debt_balance'];
	
	                $agentData['balance']=$agentTotal['balance']+$less;
	                $agentData['usage_balance']=$agentTotal['usage_balance']+$less;
	                $agentData['debt_balance'] = 0;
	
	                $data['balance_now']=$agentData['balance'];
	                $data['freeze_now']=$agentTotal['freezed_balance'];
	                $data['usage_balance_now']=$agentData['usage_balance'];
	                $data['debt_now']=$agentData['debt_balance'];
	            }else{
	                $less = $agentTotal['debt_balance']-$tradeSum;
	                $data['account_debt_balance_offset']=-$tradeSum;
	                    
	                $agentData['debt_balance'] = $less;
	                    
	                $data['balance_now']=$agentTotal['balance'];
	                $data['freeze_now']=$agentTotal['freezed_balance'];
	                $data['usage_balance_now']=$agentTotal['usage_balance'];
	                $data['debt_now']=$agentData['debt_balance'];
	            }
	        }    
            $logId = $this->accountAgentTradeLogDao->insertTradeLog($data);
            if(!empty($logId)){
               $this->UpdateTradLogSN($logId,$tradeType);
            } 
            $this->systemLogService->insertSystemLog('ADDAP',$this->getLoginUserName(),$data,array(),3); 
            $this->agentTotalDao->updateAccountAgentTotalsByUserId($agentData,$userId);    
            $this->systemLogService->insertSystemLog('ADDAP',$this->getLoginUserName(),$agentData,array('user_id'=>$userId),3);
            return true;                         	        
	   }
	   
	   /**
	    * return profit
	    */
	   public function refundProfit($userId,$tradeSum,$tradeType,$orderId,$orderNum,$tradeOperator = ""){
	        if(empty($tradeOperator)){
               $tradeOperator = $this->getTradeOperator();
            }	   	    
            $agentTotal = $this->agentTotalDao->getInfoByUserId($userId);
            if(empty($agentTotal)){
                 return false;
            }  
            $data = array();  
            $data['user_id']=$userId;
            $data['order_id']=$orderId;
            $data['order_num']=$orderNum;
            $data['trade_type']=$tradeType;
            $data['trade_sum']=$tradeSum;
            $data['trade_operator']=$tradeOperator;
            $data['status']=1;  
	        //log表交易前账户的记录
	        $data['balance_prev']=$agentTotal['balance'];
	        $data['debt_prev']=$agentTotal['debt_balance'];
	        $data['freeze_prev']=$agentTotal['freezed_balance'];
	        $data['usage_balance_prev']=$agentTotal['usage_balance']; 

	        $agentData = array();
	        $agentData['profit'] = $agentTotal['profit']-$tradeSum;

	        if($tradeSum<=$agentTotal['balance']){
	            $data['account_balance_offset']=-$tradeSum;
	            $data['account_usage_balance_offset']=-$tradeSum;
	            //          $date['account_debt_balance_offset']=-$agenttotal['debt_balance'];
	            //          $date['account_freeze_offset']=$agenttotal['debt_balance'];
	
	            $agentData['balance']=$agentTotal['balance']-$tradeSum;
	            $agentData['usage_balance']=$agentTotal['usage_balance']-$tradeSum;
	
	            $data['balance_now']=$agentData['balance'];
	            $data['freeze_now']=$agentTotal['freezed_balance'];
	            $data['usage_balance_now']=$agentData['usage_balance'];
	            $data['debt_now']=$agentTotal['debt_balance'];
            }else{
	            $less = $tradeSum-$agentTotal['balance'];
	            $debtnow = $agentTotal['debt_balance']+$less;
//	            if($debtnow<=$agentTotal['debt_total']){
	                $data['account_balance_offset']=-$agentTotal['balance'];
	                $data['account_usage_balance_offset']=-$agentTotal['balance'];
	                $data['account_debt_balance_offset']=$less;
	
	                $agentData['balance']=0;
	                $agentData['usage_balance']=$agentTotal['usage_balance']-$agentTotal['balance'];
	                $agentData['debt_balance'] =$agentTotal['debt_balance']+$less;
	                    
	                $data['balance_now']=$agentData['balance'];
	                $data['freeze_now']=$agentTotal['freezed_balance'];
	                $data['usage_balance_now']=$agentData['usage_balance'];
	                $data['debt_now']=$agentData['debt_balance'];
//	            }else{
//	                return false;
//	            }
            }
            
            $logId = $this->accountAgentTradeLogDao->insertTradeLog($data);
            if(!empty($logId)){
               $this->UpdateTradLogSN($logId,$tradeType);
            }             
            $this->systemLogService->insertSystemLog('RTNAP',$this->getLoginUserName(),$data,array(),3); 
            $this->agentTotalDao->updateAccountAgentTotalsByUserId($agentData,$userId);    
            $this->systemLogService->insertSystemLog('RTNAP',$this->getLoginUserName(),$agentData,array('user_id'=>$userId),3);
            return true;	        
	   }
	   
	   private function getTradeOperator(){
	   	   $loginUser = BaseUtil::getLoginUser();
	   	   return $loginUser['uname'];
	   }
	   
	   public function updateUserPoint($userId,$orderTotal,$orderNumber){
	   	   $user = $this->customerDao->getByCol("id",$userId);
	   	   if(!empty($user)){
	   	        $certf = $user['certf'];
	            if($certf == 1 || $certf == 6){
	                 $desc = "订单".$orderNumber."交易成功获得积分";
	                 $total = round($orderTotal);
                     $point = $user['points_buyer'] + $total;
                     $pointTotal = $user['points_buyer_total'] + $total;
                     $rank = $this->getUserRank($pointTotal);
                     //update customer point
                     $data = array();
                     $data['points_buyer'] = $point;
                     $user['points_buyer_total'] = $pointTotal;
                     $data['rank'] = $rank;
                     $this->customerDao->updateCustomer($data,$userId);
                     //insert payment log
                     $pointLog = array();
                     $pointLog['user_id'] = $userId;
                     $pointLog['type'] = 4;
                     $pointLog['point'] = $total;
                     $pointLog['current_point'] = $point;
                     $pointLog['description'] = $desc;
                     $this->userPointLogDao->insertUserPointLog($pointLog);
	            }	   	   	   
	   	   }
	   }
	   
	    /**
	     * Count user rank by point
	     */
	    protected function getUserRank($point){
	        if($point < 1000){
	            $rank = 1;
	        } else if($point < 4000){
	            $rank = 2;
	        } else if($point < 10000){
	            $rank = 3;
	        } else if($point < 25000){
	            $rank = 4;
	        } else if($point < 50000){
	            $rank = 5;
	        } else {
	            $rank = 6;
	        }
	        
	        return $rank;
	    }	   
}